<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { AlertOutlined } from "@ant-design/icons-vue";
import {
  listBalanceWarningByPage,
  addBalanceWarning,
  updateBalanceWarning,
  deleteBalanceWarning,
} from "@/api/balanceWarning";
import type {
  BalanceWarning,
  BalanceWarningQueryRequest,
  BalanceWarningAddRequest,
  BalanceWarningUpdateRequest,
} from "@/models/balanceWarning";
import dayjs from "dayjs";

// 预警类型选项
const warningTypes = [
  { value: "水费", label: "水费" },
  { value: "电费", label: "电费" },
  { value: "水电费", label: "水电费" },
];

// 余额预警管理相关状态
const warnings = ref<BalanceWarning[]>([]);
const warningTotal = ref(0);
const warningCurrentPage = ref(1);
const warningPageSize = ref(6);
const warningTypeSearch = ref("");
const warningLoading = ref(false);

// 排序信息
const sortInfo = ref({
  sortField: undefined as string | undefined,
  sortOrder: undefined as string | undefined,
});

// 预警规则编辑弹窗
const warningModalVisible = ref(false);
const warningModalTitle = ref("添加预警规则");
const editingWarning = ref<BalanceWarningUpdateRequest>({
  warningId: 0,
  thresholdValue: 0,
  warningType: "水电费",
});

// 获取预警规则列表
const fetchWarnings = async () => {
  warningLoading.value = true;
  try {
    const queryRequest: BalanceWarningQueryRequest = {
      current: warningCurrentPage.value,
      pageSize: warningPageSize.value,
      warningType: warningTypeSearch.value || undefined,
      sortField: sortInfo.value.sortField,
      sortOrder: sortInfo.value.sortOrder,
    };
    const res = await listBalanceWarningByPage(queryRequest);
    if (res.data.code === 0) {
      warnings.value = res.data.data.records;
      warningTotal.value = res.data.data.total;
    } else {
      message.error("获取预警规则列表失败");
    }
  } catch (error) {
    message.error("获取预警规则列表失败");
  } finally {
    warningLoading.value = false;
  }
};

// 搜索预警规则
const onSearch = () => {
  warningCurrentPage.value = 1;
  fetchWarnings();
};

// 重置搜索和排序
const handleReset = () => {
  warningTypeSearch.value = "";
  warningCurrentPage.value = 1;
  sortInfo.value.sortField = undefined;
  sortInfo.value.sortOrder = undefined;
  fetchWarnings();
};

// 处理表格变化（包括分页和排序）
const handleTableChange = (pagination: any, filters: any, sorter: any) => {
  warningCurrentPage.value = pagination.current;
  warningPageSize.value = pagination.pageSize;

  // 处理排序
  if (sorter.field) {
    sortInfo.value.sortField = sorter.field;
    sortInfo.value.sortOrder = sorter.order === "ascend" ? "asc" : "desc";
  } else {
    sortInfo.value.sortField = undefined;
    sortInfo.value.sortOrder = undefined;
  }

  fetchWarnings();
};

// 添加预警规则
const handleAddWarning = () => {
  warningModalTitle.value = "添加预警规则";
  editingWarning.value = {
    warningId: 0,
    thresholdValue: 0,
    warningType: "水费",
  };
  warningModalVisible.value = true;
};

// 编辑预警规则
const handleEditWarning = (record: BalanceWarning) => {
  warningModalTitle.value = "编辑预警规则";
  editingWarning.value = {
    ...record,
  };
  warningModalVisible.value = true;
};

// 删除预警规则
const handleDeleteWarning = async (record: BalanceWarning) => {
  try {
    const res = await deleteBalanceWarning(record.warningId);
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchWarnings();
    } else {
      message.error(res.data.message || "删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

// 保存预警规则
const handleSaveWarning = async () => {
  try {
    if (editingWarning.value.thresholdValue <= 0) {
      message.error("请填写有效的预警阈值");
      return;
    }

    if (editingWarning.value.warningId === 0) {
      // 添加预警规则
      const res = await addBalanceWarning(editingWarning.value);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error(res.data.message || "添加失败");
      }
    } else {
      // 更新预警规则
      const res = await updateBalanceWarning(editingWarning.value);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error(res.data.message || "更新失败");
      }
    }
    warningModalVisible.value = false;
    fetchWarnings();
  } catch (error) {
    message.error("操作失败");
  }
};

onMounted(() => {
  fetchWarnings();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <alert-outlined />
        <span>余额报警规则管理</span>
      </div>
    </template>

    <!-- 搜索区域 -->
    <template #extra>
      <a-space>
        <a-select
          v-model:value="warningTypeSearch"
          placeholder="预警类型"
          style="width: 150px"
          allowClear
        >
          <a-select-option
            v-for="type in warningTypes"
            :key="type.value"
            :value="type.value"
          >
            {{ type.label }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="onSearch">搜索</a-button>
        <a-button @click="handleReset">重置</a-button>
        <a-button type="primary" @click="handleAddWarning">
          添加预警规则
        </a-button>
      </a-space>
    </template>

    <!-- 表格区域 -->
    <a-table
      :dataSource="warnings"
      :loading="warningLoading"
      :pagination="{
        total: warningTotal,
        current: warningCurrentPage,
        pageSize: warningPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleTableChange"
    >
      <a-table-column key="warningId" title="预警ID" data-index="warningId" />
      <a-table-column
        key="thresholdValue"
        title="预警阈值"
        data-index="thresholdValue"
        :customRender="({ text }) => `￥${text.toFixed(2)}`"
      />
      <a-table-column
        key="warningType"
        title="预警类型"
        data-index="warningType"
      />
      <a-table-column
        key="createTime"
        title="创建时间"
        data-index="createTime"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')"
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <a-space>
            <a-button type="link" @click="handleEditWarning(record)"
              >编辑</a-button
            >
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条规则吗？"
              @confirm="handleDeleteWarning(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:visible="warningModalVisible"
      :title="warningModalTitle"
      @ok="handleSaveWarning"
    >
      <a-form :model="editingWarning" layout="vertical">
        <a-form-item label="预警阈值" required>
          <a-input-number
            v-model:value="editingWarning.thresholdValue"
            style="width: 100%"
            :min="0"
            :step="0.01"
            prefix="￥"
          />
        </a-form-item>
        <a-form-item label="预警类型" required>
          <a-select v-model:value="editingWarning.warningType">
            <a-select-option
              v-for="type in warningTypes"
              :key="type.value"
              :value="type.value"
            >
              {{ type.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
